package com.dmall.graph.floodfill;

public class Leetcode733 {

    private int R, C;
    private boolean[][] visited;
    private int[][] image;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        this.image = image;
        R = image.length;
        C = image[0].length;
        visited = new boolean[R][C];
        bfs(sr, sc, newColor);
        return this.image;
    }

    private void bfs(int x, int y, int color) {
        int originColor = image[x][y];
        image[x][y] = color;
        visited[x][y] = true;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty) && !visited[nextx][nexty] && image[nextx][nexty] == originColor) {
                bfs(nextx, nexty, color);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
        Leetcode733 leetcode733 = new Leetcode733();
        int[][] result = leetcode733.floodFill(image, 1, 1, 2);
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
    }
}
